package com.pn.filter;

import com.alibaba.fastjson.JSON;
import com.pn.constant.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
  自定义的全局过滤器:
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    //注入Redis模板
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //拿请求的url接口
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getPath().value();
        //1.登录请求,直接放行
        if(GatewayConstant.URLS.contains(url)){
            return chain.filter(exchange);
        }

        /*
          2.不是登录请求,判断请求是否携带token以及token是否合法
            前端一般是通过请求头Authorization来向后台归还token,而且值是bearer token;
         */
        //1>请求携带token且token合法
        List<String> authList = request.getHeaders().get(GatewayConstant.TOKEN_HEAD);
        if(!CollectionUtils.isEmpty(authList)){
            String auth = authList.get(0);
            if(StringUtils.hasText(auth)){
                String token = auth.replaceAll(GatewayConstant.TOKEN_PRE, "");
                if(StringUtils.hasText(token)&&redisTemplate.hasKey(token)){
                    return chain.filter(exchange);
                }
            }
        }

        //2>请求没有携带token或者token非法
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        Map<String, Object> date = new HashMap<>();
        date.put("code", 401);
        date.put("message", "请您先登录");
        byte[] bytes = JSON.toJSONBytes(date);
        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
